package cc.sjfx.sharedoc.activity;

import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.DrawableRes;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.ImageButton;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.RelativeLayout;
import cc.sjfx.sharedoc.R;
import cc.sjfx.sharedoc.activity.examination.HomeFragment;
import cc.sjfx.sharedoc.activity.examinfo.ExamInfoFragment;
import cc.sjfx.sharedoc.activity.release.ReleaseExamActivity;
import cc.sjfx.sharedoc.activity.release.ReleasePieceActivity;
import cc.sjfx.sharedoc.activity.release.ReleaseQuestionActivity;
import cc.sjfx.sharedoc.activity.user.UserFragment;
import cc.sjfx.sharedoc.activity.user.UserLoginActivity;
import cc.sjfx.sharedoc.bean.SetInfoBean;
import cc.sjfx.sharedoc.cache.UserCache;
import cc.sjfx.sharedoc.db.bmob.User;
import cc.sjfx.sharedoc.dialog.DialogListener;
import cc.sjfx.sharedoc.dialog.SearchDialog;
import cc.sjfx.sharedoc.dialog.SetUserInfoDialog;
import cc.sjfx.sharedoc.utils.CheckUtils;
import cc.sjfx.sharedoc.utils.StrUtils;
import cc.sjfx.sharedoc.widget.anotation.ViewInject;
import cc.sjfx.sharedoc.widget.view.floatingactionbutton.FloatingActionButton;
import cc.sjfx.sharedoc.widget.view.floatingactionbutton.FloatingActionsMenu;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.listener.UpdateListener;
import cn.mandroid.frame.toast.MLog;
import cn.mandroid.frame.toast.MToast;

public class MainActivity extends BasicFragmentActivity implements OnClickListener,
		OnCheckedChangeListener, DialogListener<SetInfoBean> {
	@ViewInject(id = R.id.rg1)
	private RadioGroup rg;
	@ViewInject(id = R.id.rb1)
	private RadioButton rb1;
	@ViewInject(id = R.id.rb2)
	private RadioButton rb2;
	@ViewInject(id = R.id.rb3)
	private RadioButton rb3;
	@ViewInject(id = R.id.right_labels)
	private FloatingActionsMenu actionsMenu;
	@ViewInject(id = R.id.fb1)
	private FloatingActionButton fb1;
	@ViewInject(id = R.id.fb2)
	private FloatingActionButton fb2;
	private int lastFragment = 1;
	@ViewInject(id = R.id.userSetImgBut)
	private ImageButton userSetImgBut;
	@ViewInject(id = R.id.cl)
	private RelativeLayout mContainer;
	private PopupWindow popupWindow;
	private SetUserInfoDialog setUserInfoDialog;
	private List<Long> nowList = new ArrayList<Long>();
	ProgressDialog releaseProgressDialog;
	ProgressDialog downloadProgressDialog;
	ReleaseComplete complete;
	long lastUpdate = 0;
	long exitTime = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		int id=getIntent().getIntExtra("fragmentId",rb1.getId());
		setFragment(id);
		setButtonVisibility(View.GONE);
		IntentFilter filter = new IntentFilter();
		filter.addAction("releaseComplete");
		filter.addAction("releaseProgress");
		filter.addAction("releaseFailed");
		filter.addAction("startDownload");
		filter.addAction("downloadFile");
		filter.addAction("finishDownload");
		complete = new ReleaseComplete();
		registerReceiver(complete, filter);
		init();
		initreleaseProgressDialog();
	}

	private void initreleaseProgressDialog() {
		// TODO Auto-generated method stub
		releaseProgressDialog = new ProgressDialog(context);
		releaseProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		releaseProgressDialog.setTitle("正在发布");
		downloadProgressDialog = new ProgressDialog(context);
		downloadProgressDialog
				.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		downloadProgressDialog.setTitle("正在下载");
	}

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		Bundle bundle = intent.getExtras();
		if (bundle != null) {
			switch (bundle.getInt("key", 0)) {
			case StrUtils.KEY_RELEASEEXAM:
				if (nowList.contains(bundle.getLong("now"))) {
					MToast.show(context, "请等待");
				} else {
					nowList.add(bundle.getLong("now"));
					MToast.show(context, "正在提交");
					addReleaseFloatingActionButton(R.id.actionButton_release,
							R.drawable.user_release_red);
				}
				break;
			case StrUtils.KEY_RELEASERETURN:
				break;
			default:
				break;
			}
		}
	}

	private void addReleaseFloatingActionButton(int id, @DrawableRes int icon) {
		// TODO Auto-generated method stub
		FloatingActionButton button = new FloatingActionButton(context);
		button.setId(id);
		button.setIcon(icon);
		button.setSize(1);
		button.setColorNormalResId(R.color.white);
		button.setColorPressedResId(R.color.white_pressed);
		actionsMenu.addButton(button);
		button.setOnClickListener(newButtonClickListener);
		actionsMenu.expand();
	}
	private void init() {
		// TODO Auto-generated method stub
		rg.setOnCheckedChangeListener(this);
		userSetImgBut.setOnClickListener(this);
		fb1.setOnClickListener(this);
		fb2.setOnClickListener(this);
	}

	private void showPopupWindow(View view) {
		// 一个自定义的布局，作为显示的内容
		View contentView = LayoutInflater.from(context).inflate(
				R.layout.popupwindow_user_setting, null);
		// 设置按钮的点击事件
		RelativeLayout r1 = (RelativeLayout) contentView
				.findViewById(R.id.popup_rl1);
		RelativeLayout r2 = (RelativeLayout) contentView
				.findViewById(R.id.popup_rl2);
		RelativeLayout r3 = (RelativeLayout) contentView
				.findViewById(R.id.popup_rl3);
		r1.setOnClickListener(listener);
		r2.setOnClickListener(listener);
		r3.setOnClickListener(listener);
		popupWindow = new PopupWindow(contentView,
				android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
				android.view.ViewGroup.LayoutParams.WRAP_CONTENT, true);
		popupWindow.setTouchable(true);
		popupWindow.setTouchInterceptor(new OnTouchListener() {
			@Override
			public boolean onTouch(View arg0, MotionEvent arg1) {
				// TODO Auto-generated method stub
				return false;
			}
		});
		popupWindow.setBackgroundDrawable(new BitmapDrawable());
		popupWindow.showAsDropDown(view);

	}

	private void logOut() {
		// TODO Auto-generated method stub
		AlertDialog.Builder builder = new Builder(context);
		builder.setTitle("确认");
		builder.setMessage("确认注销当前用户？");
		builder.setPositiveButton("是", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				// TODO Auto-generated method stub
				User.logOut(context);
				popupWindow.dismiss();
				setUserInfoDialog = null;
				rb1.setChecked(true);
			}
		});
		builder.setNegativeButton("否", null);
		builder.show();
	}

	private OnClickListener listener = new OnClickListener() {
		@Override
		public void onClick(View arg0) {
			// TODO Auto-generated method stub
			switch (arg0.getId()) {
			case R.id.popup_rl1:
				initSetInfo();
				break;
			case R.id.popup_rl2:
				logOut();
				break;
			case R.id.popup_rl3:
				break;
			default:
				break;
			}
			popupWindow.dismiss();
		}
	};

	protected void doUpdate(SetInfoBean t) {
		// TODO Auto-generated method stub
		String sign = t.getSign();
		if (!CheckUtils.stringIsNull(sign)) {
			sign = "";
		}
		User user = new User();
		user.setSign(sign);
		user.setSex(t.getSex());
		if (t.getMajorBean() != null) {
			user.setMid(t.getMajorBean().getMid());
			user.setMajor(t.getMajorBean().getMajor());
			user.setCid(t.getMajorBean().getCid());
			user.setMajor_class(t.getMajorBean().getMajor_class());
		}
		user.update(context, UserCache.user.getObjectId(),
				new UpdateListener() {
					@Override
					public void onSuccess() {
						// TODO Auto-generated method stub
						MToast.show(context, "修改成功");
						setUserInfoDialog.dismiss();
						UserCache.user = BmobUser.getCurrentUser(context,
								User.class);
						setTitle("个人中心");
						// setFragment(userFragment);
						rb2.setChecked(true);
					}

					@Override
					public void onFailure(int arg0, String arg1) {
						// TODO Auto-generated method stub
						MToast.show(context, "修改失败");
					}
				});

	}

	protected void initSetInfo() {
		// TODO Auto-generated method stub
		if (setUserInfoDialog == null) {
			setUserInfoDialog = new SetUserInfoDialog(context);
			setUserInfoDialog.setDialogListener(this);
		}
		setUserInfoDialog.show();
	}

	@Override
	public void onCheckedChanged(RadioGroup arg0, int arg1) {
		// TODO Auto-generated method stub
		switch (arg0.getId()) {
		case R.id.rg1:
			setFragment(arg1);
			break;
		default:
			break;
		}
	}

	private FragmentPagerAdapter mFragmentPagerAdapter = new FragmentPagerAdapter(
			getSupportFragmentManager()) {

		@Override
		public Fragment getItem(int position) {
			switch (position) {
			case R.id.rb1:
				return new HomeFragment();
			case R.id.rb2:
				return new UserFragment();
			case R.id.rb3:
				return new ExamInfoFragment();

			}
			return new HomeFragment();
		}

		@Override
		public int getCount() {
			return 3;
		}
	};
	Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:

				break;

			default:
				break;
			}
		}
	};

	private void setFragment(int arg1) {
		// TODO Auto-generated method stub
		switch (arg1) {
		case R.id.rb1:
			lastFragment = 1;
			setTitle("首页");
			break;
		case R.id.rb2:
			if (UserCache.isLogin) {
				lastFragment = 2;
				setTitle("个人中心");
			} else {
				if (lastFragment == 1)
					rb1.setChecked(true);
				else {
					rb3.setChecked(true);
				}
				startActivity(null, UserLoginActivity.class);
				return;
			}
			break;
		case R.id.rb3:
			lastFragment = 3;
			setTitle("考试信息");
			rb3.setChecked(true);
			break;
		default:
			break;
		}
		Fragment fragment = (Fragment) mFragmentPagerAdapter.instantiateItem(
				mContainer, arg1);
		mFragmentPagerAdapter.setPrimaryItem(mContainer, 0, fragment);
		mFragmentPagerAdapter.finishUpdate(mContainer);
		setSetButtonVisibility(lastFragment == 2 ? View.VISIBLE : View.GONE);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		MLog.i("destory");
		unregisterReceiver(complete);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.userSetImgBut:
			showPopupWindow(v);
			break;
		case R.id.fb1:
			startActivity(null, SearchDialog.class);
			break;
		case R.id.fb2:
			startShare();
			break;
		default:
			break;
		}
	}

	private DialogInterface.OnClickListener dialogClick = new DialogInterface.OnClickListener() {
		@Override
		public void onClick(DialogInterface dialog, int which) {
			// TODO Auto-generated method stub
			if (UserCache.isLogin) {
				int mid = UserCache.user.getMid();
				if (mid == 0) {
					MToast.show(context, "请先添加您所在专业");
					initSetInfo();
				} else
					switch (which) {
					case DialogInterface.BUTTON_POSITIVE:
						startActivityNeedLogin(null, ReleasePieceActivity.class);
						break;
					case DialogInterface.BUTTON_NEUTRAL:
						startActivityNeedLogin(null,
								ReleaseQuestionActivity.class);
						break;
					case DialogInterface.BUTTON_NEGATIVE:
						startActivityNeedLogin(null, ReleaseExamActivity.class);
						break;
					default:
						break;
					}
			} else {
				startActivity(null, UserLoginActivity.class);
			}
		}
	};

	private void startShare() {
		// TODO Auto-generated method stub
		AlertDialog.Builder builder = new Builder(context);
		builder.setTitle("请选择").setPositiveButton("拼试卷", dialogClick)
				.setNegativeButton("分享试卷", dialogClick)
				.setNeutralButton("问答", dialogClick).show();
	}

	private OnClickListener newButtonClickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch (v.getId()) {
			case R.id.actionButton_release:
				// startActivity(null, ReleaseExamActivity.class);
				releaseProgressDialog.show();
				// releaseProgressDialog.setProgress(50);
				break;
			case R.id.actionButton_download:
				downloadProgressDialog.show();
				break;
			default:
				break;
			}
		}
	};

	@Override
	public void buttonClick(SetInfoBean t) {
		// TODO Auto-generated method stub
		doUpdate(t);
	}

	@Override
	public void onBackPressed() {
		long t = System.currentTimeMillis();
		if (t - exitTime >= 2000) {
			exitTime = t;
			MToast.show(context, "再按一次退出");
		} else {
			exitAll();
		}

	}

	public class ReleaseComplete extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			if (intent.getAction().equals("releaseComplete")) {
				actionsMenu.removeButton(R.id.actionButton_release);
				switch (intent.getIntExtra("key", 0)) {
				case StrUtils.KEY_RELEASEEXAM:
					exitMap(StrUtils.EXIT_ACTIVITY_RELEASE);
					break;
				case StrUtils.KEY_RELEASEQUESTION:
					exitMap(StrUtils.EXIT_ACTIVITY_QUESTION);
					break;
				default:
					break;
				}
				MToast.show(context, "发布成功");
			} else if (intent.getAction().equals("releaseProgress")) {
				int pro = intent.getIntExtra("progress", 0);
				releaseProgressDialog.setProgress(pro);
				if (pro >= 99) {
					releaseProgressDialog.cancel();
				}
			} else if (intent.getAction().equals("releaseFailed")) {
				MToast.show(context, "发布失败");
			} else if (intent.getAction().equals("downloadFile")) {
				int pro = intent.getIntExtra("progress", 0);
				downloadProgressDialog.setProgress(pro);
				downloadProgressDialog.setMessage(intent
						.getStringExtra("message"));
			} else if (intent.getAction().equals("finishDownload")) {

				MToast.show(context, "下载完成");
				downloadProgressDialog.cancel();
				actionsMenu.removeButton(R.id.actionButton_download);
			} else if (intent.getAction().equals("startDownload")) {
				addReleaseFloatingActionButton(R.id.actionButton_download,
						R.drawable.download_green);
			}
		}
	}
}
